package com.nulstudio.cloud.account.controller;

import com.github.pagehelper.PageInfo;
import com.nulstudio.cloud.account.domain.dto.UserManagementDto;
import com.nulstudio.cloud.account.domain.vo.UserManagementVo;
import com.nulstudio.cloud.account.service.UserManagementService;
import com.nulstudio.cloud.common.util.NulResult;
import jakarta.annotation.Resource;
import org.springframework.lang.NonNull;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserManagementController {

    @Resource
    @NonNull
    private UserManagementService userManagementService;

    @PreAuthorize("hasAuthority('admin:read')")
    @GetMapping
    @NonNull
    public NulResult<NulResult.PageInfoResult<UserManagementVo>> all(
            @RequestParam(name = "name", defaultValue = "") @NonNull String name,
            @RequestParam(name = "page", defaultValue = "1") int page,
            @RequestParam(name = "pageSize", defaultValue = "100000") int pageSize
    ) {
        final PageInfo<UserManagementVo> pageInfo = userManagementService.fetchAll(name, page, pageSize);
        return NulResult.response(pageInfo.getList(), pageInfo.getTotal());
    }

    @PreAuthorize("hasAuthority('admin:write')")
    @PostMapping
    @NonNull
    public NulResult<Void> create(@RequestBody @NonNull UserManagementDto userManagementDto) {
        userManagementService.createUser(userManagementDto);
        return NulResult.response();
    }

    @PreAuthorize("hasAuthority('admin:write')")
    @PutMapping("/{uid}")
    @NonNull
    public NulResult<Void> update(@PathVariable int uid, @RequestBody @NonNull UserManagementDto userManagementDto) {
        userManagementService.updateUser(uid, userManagementDto);
        return NulResult.response();
    }

    @PreAuthorize("hasAuthority('admin:write')")
    @DeleteMapping("/{uid}")
    @NonNull
    public NulResult<Void> delete(@PathVariable int uid) {
        userManagementService.deleteUser(uid);
        return NulResult.response();
    }
}
